'use strict';

const Service = require('egg').Service;

class InterviewResultService extends Service {
  // 获取面试结果列表（关联简历处理表）
  async findAll(options = {}) {
    const { ctx } = this;
    const { user_id, page = 1, pageSize = 10 } = options;
    
    const offset = (page - 1) * pageSize;
    const limit = parseInt(pageSize);

    // 关联查询简历处理表
    const { count, rows } = await ctx.model.InterviewResult.findAndCountAll({
      include: [{
        model: ctx.model.ResumeProcessing,
        as: 'processingRecord',
        attributes: ['company_name', 'position_name', 'process_status', 'user_id'],
      }],
      order: [['created_at', 'DESC']],
      offset,
      limit,
    });

    // 格式化数据，将关联数据合并到主记录中
    const formattedRows = rows.map(row => {
      const plainRow = row.get({ plain: true });
      if (plainRow.processingRecord) {
        return {
          record_id: plainRow.record_id,
          processing_record_id: plainRow.processing_record_id,
          company_name: plainRow.processingRecord.company_name,
          position_name: plainRow.processingRecord.position_name,
          process_status: plainRow.processingRecord.process_status,
          user_id: plainRow.processingRecord.user_id,
          created_at: plainRow.created_at,
        };
      }
      return plainRow;
    });

    // 如果指定了 user_id，过滤结果
    const filteredRows = user_id 
      ? formattedRows.filter(row => row.user_id === parseInt(user_id))
      : formattedRows;

    return {
      data: filteredRows,
      pagination: {
        current: page,
        pageSize: pageSize,
        total: user_id ? filteredRows.length : count,
        pages: Math.ceil((user_id ? filteredRows.length : count) / pageSize)
      }
    };
  }

  // 根据ID获取面试结果详情
  async findById(id) {
    const { ctx } = this;
    const result = await ctx.model.InterviewResult.findByPk(id, {
      include: [{
        model: ctx.model.ResumeProcessing,
        as: 'processingRecord',
      }],
    });
    return result;
  }

  // 创建面试结果记录
  async create(data) {
    const { ctx } = this;
    return await ctx.model.InterviewResult.create({
      processing_record_id: data.processing_record_id,
      created_at: new Date(),
    });
  }

  // 更新面试结果记录
  async update(id, data) {
    const { ctx } = this;
    const record = await ctx.model.InterviewResult.findByPk(id);
    if (record) {
      return await record.update({
        processing_record_id: data.processing_record_id,
      });
    }
    return null;
  }

  // 删除面试结果记录
  async delete(id) {
    const { ctx } = this;
    const result = await ctx.model.InterviewResult.destroy({
      where: { record_id: id },
    });
    return result > 0;
  }
}

module.exports = InterviewResultService;
